# -*- coding: utf-8 -*-

import time
import random
import json
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA1
from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import DES
import base64
import requests

class SbyRequestUtil:

    def __init__(self):
        #des密钥
        self.INTER_KEY="930A7CE165CB2D27F62A34862A397618"
        #商户私钥
        self.MER_PRIVATE_KEY="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMhyR4I/yTdDrrI6C7HhHEH20HtbkF+wrFWoG7Rk18TatN7L6rLcW3mV3fPZUM07W7pKEGVz01grrl/OoKHbKWAEm7n+WdRXsBJ+VinVSdI0IynquDjh6qTUM8gBrPaU3KpwSdVqdY51foQw4mr7h93Bq8W6GOkgBiosQYd2yYF5AgMBAAECgYEAk6ZyfEQmIPpPLePKB45tdT2slqF8+K+4UiRRvBDoS45a2x7UVEoza510cBItDfBighfaehDWpkUO3m3jLza0A0PHmbryNsyrw0HSLiPJVaf1/wP2jvI94veXIlL1ttyKsq1kSVhgUuRS2anq/IXdaF2G1NE/rmeGatCPg0kcp7ECQQDinjgD1z8D0y+7duL8HD3+sCL94VXlGrj2DrzI75zXyuf4CBqSSRSX1lfy3HHjw5alVnmUqVQPyIK/P50JWJxlAkEA4m9iy1czgowK7DTUWOGXMVobzZdjvS168FllIJxrj3dhAvoT6MduotUoZ3e+2e9F3AoGiLGh4+NM7lmciNCthQJAb33uCx2z9/rHyhA0nlp6uboIjSV2r+/UveIESUtxu80tER9Ti1L/GbCvtmF0et04WYHQ8S3ZmKZKhTMT3IxG7QJAMoRBGTZaIozVvv7GRRIHJhaBT2uv77ueytJW0mCzSm2KshxSpsMfdqpxeivn4z0Ta9S8wnBGus2yExbg6lEL9QJBAJG8lqFuPfpzHtoCd7Xbv0GWJ+K/modlWPWbxANJQw9OL2sqQ2Was/Ipflyggu+gDDkkhePe77YkSdlAJxVNbzY="
        #商户公钥
        self.MER_PUBLIC_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIckeCP8k3Q66yOgux4RxB9tB7W5BfsKxVqBu0ZNfE2rTey+qy3Ft5ld3z2VDNO1u6ShBlc9NYK65fzqCh2ylgBJu5/lnUV7ASflYp1UnSNCMp6rg44eqk1DPIAaz2lNyqcEnVanWOdX6EMOJq+4fdwavFuhjpIAYqLEGHdsmBeQIDAQAB"
        #平台公钥
        self.YOU_FU_PUBLIC_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXFtJNcCv9X+pfOz+jy4WO+7KC0tdtDGfW/XrJOFn6mTR/TpJrsLzwssTyj0hDfUla1xDCbAWlUEkzb64jsPKk9WACupLOOrnEy7NuG0O5jg36UXle+m5/uDm8B/KGV9BQmEt+EOIbl2IzNYS4GflkbCTtkbzMc+DXetl3IHM1+wIDAQAB"
        #商户号
        self.MER_ID=1676619392976687
        #任务id
        self.TASK_ID=1607707542044405927
        #版本号
        self.API_VERSION="V1.0"
        #订单号
        self.YOU_FU_URL="http://testgateway.serviceshare.com/testapi/clientapi/clientBusiness/common"





    def applyByHttpPost(self,funCode,requestDTO):

        encryptData =  self.des_encrypt(self.INTER_KEY,requestDTO)

        data={"reqId": self.getReqId(),
              "funCode": funCode,
              "merId": self.MER_ID,
              "version": self.API_VERSION,
              "reqData": encryptData,
              "sign": self.sign(self.MER_PRIVATE_KEY,encryptData),
              }
        reqData =  json.dumps(data)
        print("请求报文:"+reqData)
        head = {"Content-Type":"application/json"}
        res = requests.post(url= self.YOU_FU_URL,data=reqData,headers=head)
        if(res.status_code != 200):
             print("响应状态码:"+str(res.status_code))
             return
        print("响应报文:"+res.text)
        data = json.loads(res.text)
        if not self.verificationSign(self.YOU_FU_PUBLIC_KEY,data['sign'],data['resData']):
            print("验签失败")
            return None
        resData = self.des_decrypt(self.INTER_KEY,data['resData'])
        print("解密响应:"+resData)
        return resData
    #生成请求reqid
    def getReqId(self):
        timestamp = int(time.time())
        # 生成四位随机数
        rand_num = str(random.randint(1000,9999))
        result = str(timestamp) + rand_num
        return result

    def des_encrypt(self,key,data):
        cipher = DES.new(key[:8].encode('utf-8'), DES.MODE_ECB)
        plaintext = pad(data.encode('utf-8'), DES.block_size)
        ciphertext = cipher.encrypt(plaintext)
        return base64.b64encode(ciphertext).decode('utf-8')

    def des_decrypt(self,key,data, ):
        cipher = DES.new(key[:8].encode('utf-8'), DES.MODE_ECB)
        ciphertext = base64.b64decode(data)
        decrypted = cipher.decrypt(ciphertext)
        return unpad(decrypted, DES.block_size).decode('utf-8')
    #生成签名
    def  sign(self,privateKey,data):
        # 将私钥字符串转换为RSA私钥对象
        private_key_str = '-----BEGIN RSA PRIVATE KEY-----'+'\n' +privateKey+'\n'+'-----END RSA PRIVATE KEY-----'
        private_key = RSA.import_key(private_key_str)
        # 创建一个签名对象，并使用SHA256哈希算法对数据进行哈希处理
        hasher = SHA1.new(data.encode('utf-8'))
        signer = pkcs1_15.new(private_key)
        # 使用私钥对数据进行签名
        signature = signer.sign(hasher)
        return  base64.b64encode(signature).decode('utf-8')
    #验签
    def verificationSign(self,publicKey,signature,message):
        public_key_str = '-----BEGIN PUBLIC KEY-----'+'\n' +publicKey+'\n'+'-----END PUBLIC KEY-----'
        # 将私钥字符串转换为RSA私钥对象
        public_key = RSA.import_key(public_key_str)
        # 创建一个签名对象，并使用SHA256哈希算法对数据进行哈希处理
        hasher = SHA1.new(message.encode('utf-8'))
        signer = pkcs1_15.new(public_key)
        try:
            signer.verify(hasher,  base64.b64decode(signature))
            return True
        except (ValueError, TypeError):
            return False


